<template>
  <div class="spc-analysis">
    <el-card>
      <div slot="header" class="card-header">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form :inline="true" :model="queryParams" class="demo-form-inline">
              <el-form-item label="产品">
                <el-select v-model="queryParams.productId" placeholder="请选择产品" clearable @change="handleProductChange">
                  <el-option v-for="item in productOptions" :key="item.id" :label="item.productName" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="批次">
                <el-select v-model="queryParams.batchId" placeholder="请选择批次" clearable :disabled="!queryParams.productId">
                  <el-option v-for="item in batchOptions" :key="item.id" :label="item.batchNo" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="测量参数">
                <el-select v-model="queryParams.paramId" placeholder="请选择参数" clearable>
                  <el-option v-for="item in paramOptions" :key="item.id" :label="item.paramName" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="时间范围" v-if="activeTab === 'trend'">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  @change="handleDateChange">
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      
      <!-- SPC分析模块选择 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="过程能力分析" name="capability">
          <process-capability-analysis 
            :loading="loadingCapability"
            :queryParams="queryParams"
            :capabilityData="capabilityData" />
        </el-tab-pane>
        <el-tab-pane label="控制图" name="control">
          <control-chart-analysis 
            :loading="loadingControl"
            :queryParams="queryParams"
            :controlChartData="controlChartData"
            @chart-type-changed="handleSpcChartTypeChange" />
        </el-tab-pane>
        <el-tab-pane label="趋势分析" name="trend">
          <trend-analysis 
            :loading="loadingTrend"
            :queryParams="queryParams"
            :trendData="trendData" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import ProcessCapabilityAnalysis from './spc/ProcessCapabilityAnalysis.vue'
import ControlChartAnalysis from './spc/ControlChartAnalysis.vue'
import TrendAnalysis from './spc/TrendAnalysis.vue'
import { listProduct } from "@/api/qep/product";
import { listBatch } from "@/api/qep/batch";
import { listParam } from "@/api/qep/param";
import { getProcessCapability, getControlChart, getSpcTrend } from "@/api/qep/dataAnalysis";

export default {
  name: "SpcAnalysis",
  components: {
    ProcessCapabilityAnalysis,
    ControlChartAnalysis,
    TrendAnalysis
  },
  data() {
    return {
      // 激活的子模块标签
      activeTab: "capability",
      
      // 产品选项
      productOptions: [],
      // 批次选项
      batchOptions: [],
      // 参数选项
      paramOptions: [],
      
      // 日期范围
      dateRange: [],
      
      // 查询参数
      queryParams: {
        productId: null,
        batchId: null,
        paramId: null,
        startDate: null,
        endDate: null
      },
      
      // 过程能力分析数据
      capabilityData: {
        capability: {},
        capabilityInterpretation: {},
        measurementDistribution: []
      },
      
      // 控制图数据
      controlChartData: {
        chartParams: {},
        measurements: [],
        chartType: "xr",
        xChartLimits: {},
        rChartLimits: {},
        pChartLimits: {}
      },
      
      // 趋势分析数据
      trendData: {
        trendData: [],
        anomalies: [],
        prediction: {}
      },
      
      // 加载状态
      loadingCapability: false,
      loadingControl: false,
      loadingTrend: false
    };
  },
  created() {
    this.getOptions();
    this.initMockData();
    this.handleQuery();
  },
  methods: {
    // 获取下拉选项数据
    getOptions() {
      // 获取产品选项
      listProduct().then(response => {
        this.productOptions = response.rows;
      });
      
      // 获取参数选项
      listParam().then(response => {
        this.paramOptions = response.rows;
      });
    },
    
    // 监听产品选择变化，更新批次选项
    handleProductChange(productId) {
      this.queryParams.batchId = null;
      this.batchOptions = [];
      
      if (productId) {
        listBatch({ productId: productId }).then(response => {
          this.batchOptions = response.rows;
        });
      }
    },
    
    // 处理日期选择变化
    handleDateChange(val) {
      if (val) {
        this.queryParams.startDate = val[0];
        this.queryParams.endDate = val[1];
      } else {
        this.queryParams.startDate = null;
        this.queryParams.endDate = null;
      }
    },
    
    // 查询按钮点击
    handleQuery() {
      this.loadData();
    },
    
    // 重置查询
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        productId: null,
        batchId: null,
        paramId: null,
        startDate: null,
        endDate: null
      };
      this.handleQuery();
    },
    
    // 标签页切换
    handleTabClick(tab) {
      // 根据切换的标签页加载相应数据
      if (tab.name === "capability") {
        this.loadCapabilityData();
      } else if (tab.name === "control") {
        this.loadControlChartData();
      } else if (tab.name === "trend") {
        this.loadTrendData();
      }
    },
    
    // 加载所有数据
    loadData() {
      if (this.activeTab === "capability") {
        this.loadCapabilityData();
      } else if (this.activeTab === "control") {
        this.loadControlChartData();
      } else if (this.activeTab === "trend") {
        this.loadTrendData();
      }
    },
    
    // 加载过程能力分析数据
    loadCapabilityData() {
      if (!this.queryParams.paramId) {
        this.$message({
          message: '请选择测量参数',
          type: 'warning'
        });
        return;
      }
      
      this.loadingCapability = true;
      getProcessCapability(this.queryParams).then(response => {
        this.capabilityData = response.data || {
          capability: {},
          capabilityInterpretation: {},
          measurementDistribution: []
        };
        this.loadingCapability = false;
      }).catch((error) => {
        console.error("加载过程能力分析数据失败:", error);
        // 使用模拟数据作为后备
        this.$message({
          message: '加载数据失败，使用模拟数据进行展示',
          type: 'warning',
          duration: 5000
        });
        // 确保已有模拟数据，如果没有则初始化
        if (!this.capabilityData.capability || Object.keys(this.capabilityData.capability).length === 0) {
          this.initMockData();
        }
        this.loadingCapability = false;
      });
    },
    
    // 加载控制图数据
    loadControlChartData() {
      if (!this.queryParams.paramId) {
        this.$message({
          message: '请选择测量参数',
          type: 'warning'
        });
        return;
      }
      
      this.loadingControl = true;
      
      const params = {
        ...this.queryParams,
        chartType: this.controlChartData.chartType
      };
      
      getControlChart(params).then(response => {
        this.controlChartData = {
          ...this.controlChartData,
          chartParams: response.data.chartParams || {},
          measurements: response.data.measurements || [],
          xChartLimits: response.data.xChartLimits || {},
          rChartLimits: response.data.rChartLimits || {},
          pChartLimits: response.data.pChartLimits || {}
        };
        this.loadingControl = false;
      }).catch((error) => {
        console.error("加载控制图数据失败:", error);
        // 使用模拟数据作为后备
        this.$message({
          message: '加载数据失败，使用模拟数据进行展示',
          type: 'warning',
          duration: 5000
        });
        // 确保已有模拟数据
        if (!this.controlChartData.measurements || this.controlChartData.measurements.length === 0) {
          this.initMockData();
        }
        this.loadingControl = false;
      });
    },
    
    // 加载趋势分析数据
    loadTrendData() {
      if (!this.queryParams.paramId) {
        this.$message({
          message: '请选择测量参数',
          type: 'warning'
        });
        return;
      }
      
      this.loadingTrend = true;
      getSpcTrend(this.queryParams).then(response => {
        this.trendData = response.data || {
          trendData: [],
          anomalies: [],
          prediction: {}
        };
        this.loadingTrend = false;
      }).catch((error) => {
        console.error("加载趋势分析数据失败:", error);
        // 使用模拟数据作为后备
        this.$message({
          message: '加载数据失败，使用模拟数据进行展示',
          type: 'warning',
          duration: 5000
        });
        // 确保已有模拟数据
        if (!this.trendData.trendData || this.trendData.trendData.length === 0) {
          this.initMockData();
        }
        this.loadingTrend = false;
      });
    },
    
    handleSpcChartTypeChange(newType) {
      this.controlChartData.chartType = newType;
      this.loadControlChartData();
    },

    // 初始化模拟数据
    initMockData() {
      // 模拟产品选项
      this.productOptions = [
        { id: 1, productName: '高压管道' },
        { id: 2, productName: '焊丝' },
        { id: 3, productName: '无缝钢管' },
        { id: 4, productName: '法兰阀门' },
        { id: 5, productName: '压力容器' }
      ];
      
      // 模拟批次选项
      this.batchOptions = [
        { id: 1, batchNo: 'HP20240101' },
        { id: 2, batchNo: 'HP20240215' },
        { id: 3, batchNo: 'HP20240310' }
      ];
      
      // 模拟参数选项
      this.paramOptions = [
        { id: 1, paramName: '外径尺寸' },
        { id: 2, paramName: '壁厚' },
        { id: 3, paramName: '圆度' },
        { id: 4, paramName: '表面粗糙度' },
        { id: 5, paramName: '硬度值' }
      ];
      
      // 模拟过程能力分析数据
      this.capabilityData = {
        capability: {
          paramName: '外径尺寸',
          usl: 102.0,
          lsl: 98.0,
          target: 100.0,
          sampleSize: 100,
          avg: 99.8,
          stdDev: 0.8,
          max: 101.5,
          min: 98.2,
          cp: 1.67,
          cpk: 1.45,
          outOfSpecRate: 0.5
        },
        capabilityInterpretation: {
          cp: '过程能力优良，变异较小',
          cpk: '过程能力良好，轻微偏离中心',
          overall: '过程能力总体表现良好，建议继续监控并适当调整过程中心'
        },
        measurementDistribution: [
          { binCenter: 98.0, frequency: 2 },
          { binCenter: 98.5, frequency: 8 },
          { binCenter: 99.0, frequency: 15 },
          { binCenter: 99.5, frequency: 25 },
          { binCenter: 100.0, frequency: 28 },
          { binCenter: 100.5, frequency: 15 },
          { binCenter: 101.0, frequency: 5 },
          { binCenter: 101.5, frequency: 2 }
        ]
      };
      
      // 模拟控制图数据
      const mockMeasurements = this.generateMockMeasurements();
      this.controlChartData = {
        chartParams: {
          paramName: '外径尺寸',
          chartType: 'xr',
          subgroupSize: 5,
          targetValue: 100.0,
          usl: 102.0,
          lsl: 98.0
        },
        measurements: mockMeasurements,
        chartType: "xr",
        xChartLimits: {
          ucl: 101.5,
          cl: 100.0,
          lcl: 98.5
        },
        rChartLimits: {
          ucl: 2.5,
          cl: 1.1,
          lcl: 0
        },
        pChartLimits: {
          ucl: 0.05,
          cl: 0.02,
          lcl: 0
        }
      };
      
      // 模拟趋势分析数据
      this.trendData = {
        trendData: this.generateMockTrendData(),
        anomalies: [
          { date: '2024-03-18', value: 101.2, type: 'high', description: '超出上控制限' },
          { date: '2024-04-05', value: 98.3, type: 'low', description: '接近下控制限' },
          { date: '2024-04-12', value: 100.8, type: 'trend', description: '连续上升趋势' }
        ],
        prediction: {
          dates: ['2024-05-01', '2024-05-08', '2024-05-15', '2024-05-22', '2024-05-29'],
          values: [100.1, 100.2, 100.3, 100.4, 100.5],
          upper: [100.8, 100.9, 101.0, 101.1, 101.2],
          lower: [99.4, 99.5, 99.6, 99.7, 99.8]
        }
      };
    },
    
    // 生成模拟测量数据
    generateMockMeasurements() {
      const measurements = [];
      const subgroupSize = 5;
      const baseDate = new Date('2024-01-01');
      
      // 生成25个子组的数据
      for (let i = 0; i < 25; i++) {
        // 创建日期，每次递增1天
        const date = new Date(baseDate);
        date.setDate(date.getDate() + i);
        const dateStr = date.toISOString().split('T')[0];
        
        // 生成每个子组的测量值
        const values = [];
        let sum = 0;
        let min = 100;
        let max = 100;
        
        for (let j = 0; j < subgroupSize; j++) {
          // 基准值100，添加一些随机变异
          let value;
          
          // 添加一些有意义的模式
          if (i > 15 && i < 20) {
            // 有一段时间数值偏高
            value = 100 + Math.random() * 1.5;
          } else if (i > 5 && i < 10) {
            // 有一段时间数值偏低
            value = 100 - Math.random() * 1.2;
          } else {
            // 正常波动
            value = 100 + (Math.random() - 0.5) * 2;
          }
          
          // 保留一位小数
          value = Math.round(value * 10) / 10;
          
          values.push(value);
          sum += value;
          min = Math.min(min, value);
          max = Math.max(max, value);
        }
        
        // 计算子组统计量
        const avg = Math.round((sum / subgroupSize) * 100) / 100;
        const range = Math.round((max - min) * 100) / 100;
        
        measurements.push({
          subgroup: i + 1,
          date: dateStr,
          values: values,
          avg: avg,
          range: range,
          min: min,
          max: max
        });
      }
      
      return measurements;
    },
    
    // 生成模拟趋势数据
    generateMockTrendData() {
      const trendData = [];
      const baseDate = new Date('2024-01-01');
      
      // 生成40个时间点的数据
      for (let i = 0; i < 40; i++) {
        // 创建日期，每次递增一周
        const date = new Date(baseDate);
        date.setDate(date.getDate() + i * 7);
        const dateStr = date.toISOString().split('T')[0];
        
        // 基准值100，添加一些趋势和周期性变化
        let value = 100 + Math.sin(i * 0.5) * 0.8; // 添加周期波动
        
        // 添加轻微上升趋势
        value += i * 0.03;
        
        // 添加一些随机噪声
        value += (Math.random() - 0.5) * 0.6;
        
        // 添加几个异常点
        if (i === 11) value += 1.2;
        if (i === 22) value -= 1.3;
        if (i === 30) value += 1.0;
        
        // 保留一位小数
        value = Math.round(value * 10) / 10;
        
        trendData.push({
          date: dateStr,
          value: value,
          usl: 102.0,
          lsl: 98.0,
          target: 100.0
        });
      }
      
      return trendData;
    }
  },
  watch: {
    'queryParams.productId': {
      handler(val) {
        this.handleProductChange(val);
      }
    }
  }
};
</script>

<style scoped>
.spc-analysis {
  background-color: #fff;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 